<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>05.案例_表单提交</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <style>
        html,
        body {
            background-color: #f8f8f8;
        }

        .login-box {
            width: 400px;
            position: fixed;
            top: 20%;
            left: 50%;
            transform: translateX(-50%);
            border: 1px solid #efefef;
            padding: 20px;
            border-radius: 4px;
            box-shadow: 1px 1px 5px #cfcfcf;
            background-color: #fff;
            transition: box-shadow 0.3s ease;
        }

        .login-box:hover {
            transition: box-shadow 0.3s ease;
            box-shadow: 1px 1px 20px #cfcfcf;
        }
    </style>
</head>

<body>
    <div class="login-box">
        <form id="myForm">
            <div class="form-group">
                <label for="username">Account</label>
                <!-- 账号 -->
                <input type="text" class="form-control" name="username" id="username" autocomplete="off">
                <small id="emailHelp" class="form-text text-muted">The available account is
                    <strong>admin</strong></small>
            </div>
            <div class="form-group">
                <!-- 密码 -->
                <label for="password">Password</label>
                <input type="password" class="form-control" name="password" id="password">
                <small id="emailHelp" class="form-text text-muted">The available password is
                    <strong>123456</strong></small>
            </div>
            <button type="submit" class="btn btn-primary" id="btnLogin">Submit</button>
        </form>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/axios@0.27.2/dist/axios.min.js"></script>
    <script src="./lib/form-serialize.js"></script>
    <script>
        document.querySelector('#btnLogin').addEventListener('click', (e) => {
            // alert(1)
            e.preventDefault()

            // 整体收集数据
            const p = serialize(document.querySelector('#myForm'), { hash: true })
            console.log(p)
            axios({
                url: 'http://hmajax.itheima.net/api/login',
                method: 'POST',
                // data: {
                //     username: p.username,
                //     password: p.password
                // },
                data: p
            }).then(res => {
                alert('成功')
            }).catch(err => {
                alert('失败')
            })
        })
    </script>
</body>

</html>